<?php

/*
 * 定时任务
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of Cron
 *
 * @author Administrator
 */
class Cron extends Basecontroll{
    private $provinceLogic;
    private $cityLogic;
    private $areaLogic;
    private $weather;
    private $weatherLogic;
    private $xinqingtempLogic;
    private $xinqingprobabilityLogic;
    private $userxinqingLogic;
    private $userLogic;
    private $xinqinglistLogic;
    public function __construct() {
        parent::__construct();
        set_time_limit(0);
        $this->provinceLogic=  $this->uselogic("Province");
        $this->cityLogic=  $this->uselogic("City");
        $this->areaLogic=  $this->uselogic("Area");
        $this->weatherLogic=  $this->uselogic("Weather");
        $this->xinqingtempLogic=  $this->uselogic("Xinqingtemp");
        $this->xinqingprobabilityLogic=  $this->uselogic("Xinqingprobability");
        $this->userxinqingLogic=  $this->uselogic("userxinqing");
        $this->userLogic= $this->uselogic("User");
        $this->xinqinglistLogic=  $this->uselogic("Xinqinglist");
        $this->weather=new WeatherApi();
     }
     public function init(){
        
        $plist=  $this->provinceLogic->getAllProvince();
        foreach ($plist as $v){
            $citylist=  $this->cityLogic->getCityListByPid($v["id"]);
            foreach ($citylist as $vv){
                $city="";
                if($vv["city"]=="市辖区"){
                    $city=$v["province"];
                }else if($vv["city"]=="县"){
                    $city=$v["province"];
                }else if($vv["city"]=="市"){
                    $city=$v["province"];
                }else{
                    $city=$vv["city"];
                }
                $code= $this->weather->getCodeByCityName($city);
                if($code!=""){
                    $update=array(
                        "weatherID"=>$code
                    );
                    $this->cityLogic->save($update,$vv["id"]);
                }
                
               
            }
            
        }
        echo 'over';
     }
     public function initArea(){
         $res=$this->areaLogic->getAll();
         foreach ($res as $v){
             $area=str_replace("市", "", $v["area"]);
             $area=str_replace("县", "", $area);
             $area=trim(str_replace("区", "", $area));
             $code= $this->weather->getCodeByCityName($area);
             $code=  str_replace("~", "", $code);
             if($code!=""){
                 $update=array(
                        "weatherID"=>$code
                    );
                 $this->areaLogic->save($update,$v["id"]);
             }
             
         }
         echo "over";
         
     }

     //put your code here
    public function catchWeather(){
        $plist=  $this->provinceLogic->getAllProvince();
        foreach ($plist as $v){
            $citylist=  $this->cityLogic->getCityListByPid($v["id"]);
            foreach ($citylist as $vv){
                if($vv["weatherID"]&&!$this->weatherLogic->existCity_id($vv["id"])){
                    $data=$this->weather->getTodayWeather($vv["weatherID"]);
                    $data["all"]["city_id"]=$vv["id"];
                    $data["all"]["create_time"]=  strtotime(date("Y-m-d")." 00:00:00");
                    if(isset($data["all"]["cityname"])){
                        if(!$this->weatherLogic->existCity_name($data["all"]["cityname"])){
                            $this->weatherLogic->save($data["all"]);
                        }
                    }else{
                        echo "id:{$vv["id"]},name:{$vv["city"]}获取失败,url:"."http://d1.weather.com.cn/sk_2d/{$code}.html?_=".time()."<br/>";
                    }
                }
            }
        }
        echo "over";
        
    }
    
    //获得天气的 实时数据,3小时更新一次
    public function getRelWeather(){
        $citylist=$this->cityLogic->getHasWeatherAll();
        foreach ($citylist as $v){
            if($v["weatherID"]){
                
                    $data=  $this->weather->getRelParty($v["weatherID"]);
                    //$this->weatherLogic->begin();
                    try{
                        if(!empty($data)&&!$this->weatherLogic->existWeather_id($data["weatherID"])&&$v["weatherID"]==$data["weatherID"]){
                                $data["city_id"]=$v["id"];
                                $data["create_time"]=  strtotime(date("Y-m-d")." 00:00:00");
                                $data["edit_time"]=  date("Y-m-d H:i:s",  time());
                                $this->weatherLogic->save($data);
                                //$this->weatherLogic->commit();
                        }else if(!empty($data)&&$this->weatherLogic->existWeather_id($data["weatherID"])&&$v["weatherID"]==$data["weatherID"]){
                            $weather_data=  $this->weatherLogic->getWeatherByWeatherID($data["weatherID"]);
                            if(!empty($weather_data)){
                                if(intval($weather_data["id"])>0){
                                    $data["edit_time"]=  date("Y-m-d H:i:s",time());
                                    $this->weatherLogic->save($data,$weather_data["id"]);
                                    //$this->weatherLogic->commit();
                                }
                            }
                        }else{
                            //$this->weatherLogic->rollback();
                        }
                    }  catch (Exception $e){
                        //$this->weatherLogic->rollback();
                    }
                
            }
        }
        echo "over";
    }
    //获得天气的信息 非实时部分 一天更新一次
    public function getNrelWeather(){
        set_time_limit(10800);
        while (TRUE){
            $weatherlist=  $this->weatherLogic->getNeedToUpdateWeather();
            if($weatherlist==FALSE){
                break;
            }
            foreach ($weatherlist as $v){
                
                if(time_nanosleep(0,900000)){
                    $this->getSingleNrelWeather2($v["id"], $v["weatherID"]);
                }
            }
        }
        echo "over";
    }
    
    //获得天气的信息 非实时部分 一天更新一次
    private function getSingleNrelWeather2($id=0,$weatherID=FALSE){
        if($weatherID&&$id){
           $data=  $this->weather->getNrelParty($weatherID);
     
           if(intval($id)>0){
              $data["edit_time2"]=  date("Y-m-d H:i:s",time());
              $this->weatherLogic->save($data,$id);
           }
        }
    }
    
    
    //获得天气的信息 非实时部分 一天更新一次
    public function getSingleNrelWeather(){
        $id=  isset($_GET["id"])?intval($_GET["id"]):0;
        $weatherID=isset($_GET["weatherID"])?$_GET["weatherID"]:FALSE;
        
        if($weatherID&&$id){
           $data=  $this->weather->getNrelParty($weatherID);
     
           if(intval($id)>0){
              $data["edit_time2"]=  date("Y-m-d H:i:s",time());
              $this->weatherLogic->save($data,$id);
           }
        }
    }
    //获得天气的 实时数据,3小时更新一次 地区
    public function getAreaRelWeather(){
        $arealist=$this->areaLogic->getHasWeatherAll();
        foreach ($arealist as $v){
            if($v["weatherID"]){
                    $data=  $this->weather->getRelParty($v["weatherID"]);
                   // $this->weatherLogic->begin();
                    try{
                        if(!empty($data)&&!$this->weatherLogic->existWeather_id($data["weatherID"])&&$v["weatherID"]==$data["weatherID"]){
                                $data["area_id"]=$v["id"];
                                $data["create_time"]=  strtotime(date("Y-m-d")." 00:00:00");
                                $data["edit_time"]=  date("Y-m-d H:i:s",  time());
                                $this->weatherLogic->save($data);
                                //$this->weatherLogic->commit();
                        }else if(!empty($data)&&$this->weatherLogic->existWeather_id($data["weatherID"])&&$v["weatherID"]==$data["weatherID"]){
                            $weather_data=  $this->weatherLogic->getWeatherByWeatherID($data["weatherID"]);
                            if(!empty($weather_data)){
                                if(intval($weather_data["id"])>0){
                                    $data["edit_time"]=  date("Y-m-d H:i:s",time());
                                    $this->weatherLogic->save($data,$weather_data["id"]);
                                    //$this->weatherLogic->commit();
                                }
                            }
                        }else{
                             //$this->weatherLogic->rollback();
                        }
                    }  catch (Exception $e){
                        //$this->weatherLogic->rollback();
                    }
              
            }
        }
        echo "over";
    }
    //获得第二天的天气信息
    public function getTomorrowCityWeather(){
        $tomorrow_tmp=strtotime("+1 day");
        $d=  date("Y-m-d",$tomorrow_tmp)." 00:00:00";
        $tomorrow=  strtotime($d);
        $citylist=$this->cityLogic->getHasWeatherAll();
        foreach ($citylist as $v){
            if($v["weatherID"]){
                $data=$this->weather->getTomorrowWeather($v["weatherID"]);
                if($data&&!$this->weatherLogic->existWeather_id($v["weatherID"],$tomorrow)){
                    $data["create_time"]=$tomorrow;
                    $data["city_id"]=$v["id"];
                    $data["edit_time"]=  date("Y-m-d H:i:s",  time());
                    $this->weatherLogic->save($data);
                }elseif($data&&$this->weatherLogic->existWeather_id($v["weatherID"],$tomorrow)){
                    $weather_data=  $this->weatherLogic->getWeatherByWeatherID($v["weatherID"],$tomorrow);
                    if(!empty($weather_data)){
                        if(intval($weather_data["id"])>0){
                           $data["edit_time"]=  date("Y-m-d H:i:s",time());
                           $this->weatherLogic->save($data,$weather_data["id"]);
                        }
                    }
                }
            }
        }
        
        
       
       echo "over"; 
        
        
    }
     //获得第二天的天气信息
    public function getTomorrowAreaWeather(){
        $tomorrow_tmp=strtotime("+1 day");
        $d=  date("Y-m-d",$tomorrow_tmp)." 00:00:00";
        $tomorrow=  strtotime($d);
        $arealist=$this->areaLogic->getHasWeatherAll();
        foreach ($arealist as $v){
            if($v["weatherID"]){
                $data=$this->weather->getTomorrowWeather($v["weatherID"]);
                if($data&&!$this->weatherLogic->existWeather_id($v["weatherID"],$tomorrow)){
                    $data["create_time"]=$tomorrow;
                    $data["area_id"]=$v["id"];
                    $data["edit_time"]=  date("Y-m-d H:i:s",  time());
                    $this->weatherLogic->save($data);
                }elseif($data&&$this->weatherLogic->existWeather_id($v["weatherID"],$tomorrow)){
                    $weather_data=  $this->weatherLogic->getWeatherByWeatherID($v["weatherID"]);
                    if(!empty($weather_data)){
                        if(intval($weather_data["id"])>0){
                           $data["edit_time"]=  date("Y-m-d H:i:s",time());
                           $this->weatherLogic->save($data,$weather_data["id"]);
                        }
                    }
                }
            }
        }
        echo "over"; 
    }
    public function txt(){
        for($i=0;$i<10;$i++){
            echo 'xxxxxx<br/>';
            ob_flush();
            flush();
            sleep(10);
            echo "nnnnnnn<br/>";
        }
        
    }
    //统计用户心情和温度的关系
    public function getXinQingTemp(){
        $this->xinqingtempLogic->deleteAll();
        $sql="INSERT into jp_xinqing_temp(user_id,xinqing_id,`month`,`day`,temp,count,weight) SELECT user_id,xinqing_id,`month`,`day`,temp,COUNT(temp)as count,COUNT(temp)/100-(sum(hum_temp_weight))/100 as weight from jp_user_xinqing GROUP BY `month`,`day`,user_id,xinqing_id,temp";
        $this->xinqingtempLogic->query($sql);
        echo '执行成功！';
    }
    
    //计算用户心情平均温度
    public function avgTemp(){
        $sql="select a.*,l.base_name as xinqing_name,u.nickname from (SELECT avg(temp) as avg_temp,user_id,xinqing_id,`month`,`day` from jp_xinqing_temp GROUP BY user_id,xinqing_id,`month`,`day`) as a LEFT JOIN jp_xinqinglist as l on a.xinqing_id=l.id LEFT JOIN jp_user as u on a.user_id=u.id";
        $row=$this->xinqingtempLogic->execute($sql);
        foreach ($row as $v){
            if($this->xinqingprobabilityLogic->exist_probability($v["user_id"],$v["xinqing_id"],$v["month"],$v["day"])){
                $p=  $this->xinqingprobabilityLogic->getProbability($v["user_id"],$v["xinqing_id"],$v["month"],$v["day"]);
                $this->xinqingprobabilityLogic->save($v,$p["id"]);
            }else{
                $this->xinqingprobabilityLogic->save($v);
            }
        }
        echo "over！";
    }
    /**
     * 计算用户心情概率值
     */
    public function probXinqing(){
        $data=$this->userxinqingLogic->getProbList();
        foreach ($data as $v){
            $data=array(
                "user_id"=>$v["user_id"],
                "xinqing_id"=>$v["xinqing_id"],
                "prob"=>$v["p"],
                "prob_num"=>$v["prob"],
                "prob_all"=>$v["allcount"],
                "month"=>$v["month"],
                "day"=>$v["day"],
            );
            $user=$this->userLogic->getOne("id={$v["user_id"]}");
            $xinqing=  $this->xinqinglistLogic->getOne("id={$v["xinqing_id"]}");
            if(isset($user["nickname"])&&$user["nickname"]!=""){
                $data["nickname"]=$user["nickname"];
            }
            if(isset($xinqing["base_name"])&&$xinqing["base_name"]!=""){
                $data["xinqing_name"]=$xinqing["base_name"];
            }
            if($this->xinqingprobabilityLogic->exist_probability($v["user_id"],$v["xinqing_id"],$v["month"],$v["day"])){
                $prob=$this->xinqingprobabilityLogic->getProbability($v["user_id"],$v["xinqing_id"],$v["month"],$v["day"]);
                if($prob&&isset($prob["id"])){
                    $this->xinqingprobabilityLogic->save($data,$prob["id"]);
                }
            }else{
                $this->xinqingprobabilityLogic->save($data);
            }
            //$this->xinqingprobabilityLogic->save();
        }
        echo "over!";
    }
}
